package sim1011.examples.kame.test;

import java.util.Random;

import jade.core.AID;
import jade.core.Agent;
import jade.core.behaviours.OneShotBehaviour;
import jade.domain.DFService;
import jade.domain.FIPAException;
import jade.domain.FIPAAgentManagement.DFAgentDescription;
import jade.domain.FIPAAgentManagement.ServiceDescription;
import jade.lang.acl.ACLMessage;

public class Component extends Agent {
	private static final long serialVersionUID = -572439546594544346L;
	private AID[] components;
	public int reqCPU = 20;
	public int reqMem = 10;
	
	protected void setup() {
		System.out.println("started setup " + getAID().getName());
		DFAgentDescription dfd = new DFAgentDescription();
		dfd.setName(getAID());
		ServiceDescription sd = new ServiceDescription();
		sd.setType("sim-type");
		sd.setName("sim-component");
		dfd.addServices(sd);
		try {
			DFService.register(this, dfd);
		} catch (FIPAException fe) {
			fe.printStackTrace();
		}
		addBehaviour(new ComponentBehaviour());
		addBehaviour(new OneShotBehaviour() {
			
			@Override
			public void action() {
				System.out.println("sending first message");
				sendMessage();
			}
			
			private void sendMessage() {
				DFAgentDescription template = new DFAgentDescription();
				ServiceDescription sd = new ServiceDescription();
				sd.setType("sim-type");
				template.addServices(sd);
				try {
					DFAgentDescription[] result = DFService.search(myAgent, template); 
					components = new AID[result.length];
					for (int i = 0; i < result.length; ++i) {
						components[i] = result[i].getName();
					}
					//System.out.println(result.length);
					if (result.length != 0) {
						Random r = new Random(System.currentTimeMillis());
						int nr = -1;
						boolean found = false;
						int who = -1;
						while (!found) {
							nr = r.nextInt();
							who = (Math.abs(nr))%(result.length);
							if (!components[who].getName().equalsIgnoreCase(getAID().getName()))
								found = true;
						}
						System.out.println("r=" +nr+ " who="+who);
						ACLMessage req = new ACLMessage(ACLMessage.PROPAGATE);
						req.addReceiver(components[who]);
						myAgent.send(req);
					}
				} catch (FIPAException fe) {
					fe.printStackTrace();
				}
			}
		});
	}
	
	protected void takeDown() {
		try {
			DFService.deregister(this);
		} catch (FIPAException fe) {
			fe.printStackTrace();
		}
	}
}
